package com.li.service.impl;

import com.li.exception.BaseException;
import com.li.pojo.po.Menu;
import com.li.mapper.MenuMapper;
import com.li.pojo.vo.MenuVO;
import com.li.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-04-13
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> getMenuList(String menuName, String status) {
        List<Menu> list = menuMapper.getMenuList(menuName,status);
        return list;
    }

    @Override
    public List<MenuVO> treeSelectMenu() {
        List<Menu> list = menuMapper.getAll();
        List<MenuVO> menuVOS = new ArrayList<>();
        for (Menu menu : list) {
            //说明是一级菜单
            if((menu.getParentId()) == 0){
                MenuVO menuVO = new MenuVO();
                menuVO.setId(menu.getMenuId());
                menuVO.setLabel(menu.getMenuName());
                List<MenuVO> children = getChildren(list,menu.getMenuId());
                menuVO.setChildren(children);
                menuVOS.add(menuVO);
            }
        }
        return menuVOS;
    }

    @Override
    public void addMenu(Menu menu) {
        menu.setCreateBy("admin");
        menu.setUpdateBy("admin");
        menu.setCreateTime(LocalDateTime.now().toString());
        menu.setUpdateTime(LocalDateTime.now().toString());
        menuMapper.insert(menu);
    }

    @Override
    public void updateMenu(Menu menu) {
        menu.setUpdateTime(LocalDateTime.now().toString());
        menuMapper.updateMenu(menu);
    }

    @Override
    public void deleteMenuId(Long menuId) {
        //查看当前菜单下是否还有子菜单
        List<Menu> list = menuMapper.selectParentId(menuId);
        if(!CollectionUtils.isEmpty(list)){
            throw new BaseException("当前菜单下存在子菜单，不允许删除");
        }
        removeById(menuId);
    }

    /**
     * 递归查询菜单
     * @param list
     * @param menuId
     * @return
     */
    private List<MenuVO> getChildren(List<Menu> list, Long menuId) {
        List<MenuVO> menuVOS = new ArrayList<>();
        for (Menu menu : list) {
            if(menuId.equals(menu.getParentId())){
                MenuVO menuVO = new MenuVO();
                menuVO.setId(menu.getMenuId());
                menuVO.setLabel(menu.getMenuName());
                List<MenuVO> children = getChildren(list,menu.getMenuId());
                menuVO.setChildren(children);
                menuVOS.add(menuVO);
            }
        }
        return menuVOS;
    }
}
